﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static DevExpress.Xpo.Helpers.AssociatedCollectionCriteriaHelper;

namespace WinForm_Mes.WorkingManagement.TeamSet
{
    public partial class TeamSetForm : DevExpress.XtraEditors.XtraForm
    {
        public TeamSetForm()
        {
            InitializeComponent();
            this.IsMdiContainer = false;
            
            // 初始化表单时首先加载团队类型下拉框数据
            InitTeamTypeComboBox();
            
            GetTeamSetList();
            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CheckBoxRowSelect;
        }

        // 初始化团队类型下拉框数据
        private async void InitTeamTypeComboBox()
        {
            try
            {
                // 初始化下拉框显示格式
                comboBoxEdit1.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
                
                // 获取团队类型列表
                var teamTypeList = await GetAllTeamTypes();
                if (teamTypeList != null && teamTypeList.Count > 0)
                {
                    // 设置数据源，使用Dictionary存储Id和Name
                    var dataSource = new Dictionary<string, string>();
                    dataSource.Add("", "全部"); // 添加一个空选项
                    
                    foreach (var item in teamTypeList)
                    {
                        dataSource.Add(item.id.ToString(), item.teamTypeName);
                    }
                    
                    // 绑定到下拉框
                    comboBoxEdit1.Properties.Items.Clear();
                    foreach (var item in dataSource)
                    {
                        comboBoxEdit1.Properties.Items.Add(new ComboBoxItem { Value = item.Key, Display = item.Value });
                    }
                    
                    // 默认选中全部
                    comboBoxEdit1.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载团队类型数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 获取所有团队类型数据
        private async Task<List<TeamTypeItem>> GetAllTeamTypes()
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    var response = await HttpClientHelper.RequestUrl(RequestType.get,MethodGolab.SHOW_DEFECT + "?PageIndex=1&PageSize=1000");
                    //序列化
                    var result = JsonConvert.DeserializeObject<TeamTypeResponse<TeamTypeItem>>(response);
                    if (result.code == 200)
                    {
                        return result.items;
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show($"获取团队类型列表失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                return new List<TeamTypeItem>();
            }
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            // 获取选中行
            int[] selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("请选择要修改的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (selectedRows.Length > 1)
            {
                XtraMessageBox.Show("只能选择一条记录进行修改", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 获取选中行的数据
            TeamSetModel selectedTeamSet = gridView1.GetRow(selectedRows[0]) as TeamSetModel;
            if (selectedTeamSet != null)
            {
                // 打开修改窗口
                UpdateTeamSetForm updateForm = new UpdateTeamSetForm(selectedTeamSet);
                updateForm.UpdateTeamSetEvent += GetTeamSetList;
                updateForm.ShowDialog();
            }
        }

        private string TeamSetCode = "";
        private string TeamSetName = "";
        private string TeamTypeId = "";
        private int total = 0;
        private int pageIndex = 1;
        private int pageSize = 10;
        private int pageCount = 0;
        public async void GetTeamSetList()
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    TeamSetCode = textEdit1.Text.Trim();
                    TeamSetName = textEdit2.Text.Trim();
                    // 获取选中项的Value值作为TeamTypeId
                    TeamTypeId = "";
                    if (comboBoxEdit1.SelectedItem is ComboBoxItem selectedItem)
                    {
                        TeamTypeId = selectedItem.Value;
                    }

                    
                    var datacom = new FormUrlEncodedContent(new Dictionary<string, string>{
                    { "TeamSetCode",TeamSetCode},
                    { "TeamSetName",TeamSetName},
                    { "TeamTypeId",TeamTypeId},
                    });
                    var context = JsonConvert.SerializeObject(datacom);
                    var url = $"?TeamSetCode={TeamSetCode}&TeamSetName={TeamSetName}&TeamTypeId={TeamTypeId}&PageIndex={pageIndex}&PageSize={pageSize}";
                    var response = await HttpClientHelper.RequestUrl(RequestType.get, MethodGolab.SHOW_SETDEFECT+url);
                    var result = JsonConvert.DeserializeObject<TeamSetResponse<TeamSetModel>>(response);
                    if (result.code == 200 && result.items != null)
                    {
                        gridControl1.DataSource = result.items;
                        total = result.total;
                        pageCount = (int)Math.Ceiling((double)total / pageSize);
                        labelControl4.Text = $"共 {result.total} 条记录,当前第{pageIndex}/{pageCount}页";
                    }
                    else
                    {
                        XtraMessageBox.Show($"查询失败：{result.message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {

                    XtraMessageBox.Show($"发生异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                
                
            }
        }

        private void TeamSetForm_Load(object sender, EventArgs e)
        {

        }

        private void TeamSetClick(object sender, EventArgs e)
        {
            GetTeamSetList();
        }

        private void ResetClick(object sender, EventArgs e)
        {
            
            textEdit1.Text = "";
            
            textEdit2.Text = "";
            // 获取选中项的Value值作为TeamTypeId
            comboBoxEdit1.SelectedItem = null;
        }

        private  void simpleButton3_Click(object sender, EventArgs e)
        {
            AddTeamSetForm addTeamSetForm = new AddTeamSetForm();
            addTeamSetForm.AddTeamSetEvent += GetTeamSetList;
            addTeamSetForm.ShowDialog();
        }


        private async void simpleButton5_Click(object sender, EventArgs e)
        {
            // 获取选中行
            int[] selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("请选择要删除的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 确认删除
            DialogResult result = XtraMessageBox.Show("确定要删除选中的记录吗？", "确认",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result != DialogResult.Yes)
            {
                return;
            }

            try
            {
                // 收集所有选中行的ID
                List<long> idsToDelete = new List<long>();
                foreach (int rowHandle in selectedRows)
                {
                    TeamSetModel item = gridView1.GetRow(rowHandle) as TeamSetModel;
                    if (item != null)
                    {
                        idsToDelete.Add(item.id);
                    }
                }

                // 逐个删除选中的记录
                int successCount = 0;
                foreach (long id in idsToDelete)
                {
                    var url = $"?id={id}";
                    var response = await HttpClientHelper.RequestUrl(RequestType.post, MethodGolab.POST_SETDELETE + url);
                    var resultData = JsonConvert.DeserializeObject<TeamSetResponse<TeamSetModel>>(response);

                    if (resultData.code == 200)
                    {
                        successCount++;
                    }
                    else
                    {
                        XtraMessageBox.Show($"删除ID为{id}的记录失败：{resultData.message}", "错误",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                // 显示删除结果
                if (successCount > 0)
                {
                    XtraMessageBox.Show($"成功删除{successCount}条记录", "成功",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // 刷新列表
                    GetTeamSetList();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"删除操作发生异常：{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 在TeamSetForm中添加人员按钮点击事件中
        private void EmployeeUpdate_Click(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            // 获取当前编辑器
            var edit = sender as DevExpress.XtraEditors.ButtonEdit;

            // 获取当前行
            int rowHandle = gridView1.FocusedRowHandle;

            // 获取该行的数据
            TeamSetModel teamSet = gridView1.GetRow(rowHandle) as TeamSetModel;
            EmployeeForm form = new EmployeeForm(teamSet.id, teamSet.teamSetName);

            form.ShowDialog();
        }

        private void EmployeeShow_Click(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            // 获取当前编辑器
            var edit = sender as DevExpress.XtraEditors.ButtonEdit;

            // 获取当前行
            int rowHandle = gridView1.FocusedRowHandle;

            // 获取该行的数据
            TeamSetModel teamSet = gridView1.GetRow(rowHandle) as TeamSetModel;
            if (teamSet != null)
            {
                // 打开班组成员详情窗体，传入班组ID和名称
                TeamSetEmployeeForm employeeForm = new TeamSetEmployeeForm(teamSet.id, teamSet.teamSetName);
                employeeForm.TeamSetEmployeeEvent += GetTeamSetList; // 注册事件，操作成功后刷新列表
                employeeForm.ShowDialog();
            }
            
        }
    }
}

// 为下拉框项目定义一个类
public class ComboBoxItem
{
    public string Value { get; set; }  // 存储ID值
    public string Display { get; set; } // 显示的名称
    
    public override string ToString()
    {
        return Display;
    }
}

public class TeamSetResponse<T>
{
    public int total { get; set; }
    public int pageIndex { get; set; }
    public int pageSize { get; set; }
    public T[] items { get; set; }
    public int code { get; set; }
    public string message { get; set; }
    public object data { get; set; }
}

public class TeamSetModel
{
    public long id { get; set; }
    public string teamSetCode { get; set; }
    public long teamTypeId { get; set; }
    public string teamTypeName { get; set; }
    public string teamSetName { get; set; }
    public string teamLeader { get; set; }
    public string remark { get; set; }
}

// 添加TeamTypeItem类，用于解析API返回的团队类型数据
public class TeamTypeItem
{
    public long id { get; set; }
    public string teamTypeCode { get; set; }
    public string teamTypeName { get; set; }
    public string createUser { get; set; }
    public string createTime { get; set; }
    public string remark { get; set; }
}

// TeamTypeResponse类用于解析API返回的团队类型列表
public class TeamTypeResponse<T>
{
    public int total { get; set; }
    public int pageIndex { get; set; }
    public int pageSize { get; set; }
    public List<T> items { get; set; }
    public int code { get; set; }
    public string message { get; set; }
    public object data { get; set; }
}


